function getJSONData(url,callback){
    $.ajax({
        type: "get",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: url,  //这里是网址
        success: function (json) {
            callback(json)
        },
        timeout: 90*1000,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.error(url,textStatus+": "+errorThrown);
        }
    });
}
function RMS(s){
  return s.replace('市','');//.replace('特别行政区','');
}
var host='http://58.213.141.220:8989/njhbindex';
  
  //生成12个月的下拉
  var currentMonth = (new Date()).pattern("M")-1,
      currentYear = (new Date()).pattern("yyyy"),
      currentDay=(new Date()).pattern("dd");
  if(currentMonth==0){
    currentMonth=12;
    currentYear-=1;
  }
  currentMonth=currentMonth<10?'0'+currentMonth:currentMonth;
    var monthArray = function (cy,cm) {
        var result = [];
        for(var y=cy;y>2015;y--){
            if(cy==y){
                for(;cm>=1;cm--){
                    result.push(y+'-'+paddingZero(cm));
                }
            }else{
                for(var m=12;m>=1;m--){
                    result.push(y+'-'+paddingZero(m));
                }
            }
        }
        return result;
    }
    function paddingZero(m){
        if(m.length>1) return m;
        return m < 10 ? "0" + m : m;
    }
     
  var tmpselect=''; 
    monthArray(currentYear,currentMonth).forEach(function(e,v){
        tmpselect+='<option value="'+e+'">'+e.replace(/-/g,'年')+'月</option>';
  });
  $('#ylv-month-select').html(tmpselect);
    tmpselect+='<option value="2015-12">2015年</option>';
    $('#month-select').html(tmpselect);
  // 月份切换
    $('#ylv-month-select').change(function(){
      setYlvChart($(this).val());
    });
    // 月份切换
    $('#month-select').change(function(){
      setSortTable($(this).val());
    });
    
    var areas={
      1:["南京开发区","2008","仙林大学城",-13,1],
      2:["栖霞区","2008,2007","仙林大学城,迈皋桥",-13,2],
      3:["建邺区","2009","奥体中心",-13,3],
      4:["高新开发区","2010","浦口",-13,4],
      5:["浦口区","2010","浦口",-13,5],
      6:["玄武区","2004","玄武湖",-13,6],
      7:["鼓楼区","2001,2006","草场门，山西路",-13,7],
      8:["秦淮区","2003","瑞金路",-13,8],
      9:["六合区","2022","雄州",-4,9],
      10:["江宁开发区","2018","将军大道",-13,10],
      11:["雨花台区","2002","中华门",-13,11],
      12:["南京化工园","2011","化工园",-13,12],
      13:["高淳区","2013","淳溪",-2,13],
      14:["江宁区","2016","彩虹桥",-4,14],
      15:["溧水区","2024","永阳",-2,15],
      16:["全市","2000","全市",-13,16]
    },areas2014={
      9:'*',
      13:'*',
      14:'*',
      15:'*',
    };
  getJSONData(host+'/data?act=areainfo',function(data){
    var trs=[];
    if(data.Error==null){
      //重新排列
      var tmpData = [];
      tmpData[0] = data.Data[5];
      tmpData[1] = data.Data[7];
      tmpData[2] = data.Data[2];
      tmpData[3] = data.Data[6];
      tmpData[4] = data.Data[1];
      tmpData[5] = data.Data[10];
      tmpData[6] = data.Data[4];
      tmpData[7] = data.Data[13];
      tmpData[8] = data.Data[8];
      tmpData[9] = data.Data[14];
      tmpData[10] = data.Data[12];
      tmpData[11] = data.Data[9];
      tmpData[12] = data.Data[0];
      tmpData[13] = data.Data[3];
      tmpData[14] = data.Data[11];
      tmpData[15] = data.Data[15];
      data.Data = tmpData;
      data.Data.forEach(function(e,i){
        areas[e.id][0]=e.name;
        areas[e.id][1]=e.codes;
        areas[e.id][2]=e.areas;
        areas[e.id][3]=e.target;
        areas[e.id][4]=e.index;
        trs.push('<tr id="st-'+e.id+'"><td>'+e.name+(areas2014[e.id]!=undefined?'*':'')+'</td><td></td><td></td><td></td><td></td></tr>');
      });
    }
    $('#sorttable').html(trs.join(''));
    var _currentYear=currentYear,
        _currentMonth=currentMonth;
    // if(currentDay<15) _currentMonth-=1;
    if(_currentMonth==0){
      _currentMonth=12;
      _currentYear-=1;
    }else if(_currentMonth==-1){
      _currentMonth=11;
      _currentYear-=1;
    }
    setSortTable(_currentYear+'-'+paddingZero(_currentMonth));
  });
  function setSortTable(month){
    $('#month-select').val(month);
    var qstr=month.split('-');
    var curmstr=qstr[0]+'/'+qstr[1];
    $('#order-month-warp').find('td').eq(0).html(curmstr);
    getJSONData(host+'/data?act=areamonth&month='+month,function(data){
      if(data.Error==null){
        data.Data.forEach(function(e){
          var tds=$('#st-'+e.areaid).find('td')
            ,g1=getGrowth(e.value,e.hbrate)
            ,g2=getGrowth(e.value,e.tbrate);
          tds.eq(1).html(e.value);
          tds.eq(2).html(g1+'%').css('color',g1<0?'#09c900':'#ff6000');
          tds.eq(3).html(g2+'%').css('color',g2<0?'#09c900':'#ff6000');
        });
      }
    });
    getJSONData(host+'/data?act=areayear&year='+qstr[0],function(data){
      if(data.Error==null){
        data.Data.forEach(function(e){
          var pm25,jzpm25,id=e.areaid;
          if(parseInt(qstr[0])==2016){
            if(e.monthtype==200+parseInt(qstr[1])){
              pm25=e.pm25;
              jzpm25=e.jzpm25;
            }else if(e.monthtype==200+parseInt(qstr[1])-1){
              pm25=e.pm25;
              jzpm25=e.jzpm25;
            }
          }else{
            pm25=e.pm25;
            jzpm25=e.jzpm25;
          }
          if(pm25!=undefined&&jzpm25!=undefined){
            var g3=getGrowth(pm25,jzpm25);
            $('#st-'+id).find('td').eq(4).html(g3+'%<i class="targetNum">('+areas[id][3]+'%)</i>').css('color',g3<areas[id][3]?'#09c900':'#ff6000');
          }
        });
      }
    });
  }
    function getGrowth(v1,v2){
    if(v1==''||v2=='') return '';
    return (((v1-v2)/v2)*100).toFixed(2);
  }
  
  var __gauge;
  var c1={
        borderColor:'#CBE7F5',
        innerBorderColor:'#D1E9F6',
        arrowColor:'#00A8E0',
        startColor:'#00A8E0',
        endColor:'#72CD2C',
        waveColor:'#72CD2C',
        minValue: 0,
        maxValue: 150,
        img:{
            width:28,
            height:50,
            src:'assets/img/ylvicon.png'
        },
        title:'空气质量优良率'
    };
var c2={
    borderColor:'#F5E7E4',
    innerBorderColor:'#FDD0BB',
    arrowColor:'#E85800',
    startColor:'#E85800',
    endColor:'#F48C70',
    waveColor:'#E85800',
    minValue: 0,
    maxValue: 150,
    img:{
        width:28,
        height:50,
        src:'assets/img/ylvicon.png'
    },
    title:'优良天数'
}
function setYlvChart(month){
    $('#ylv-month-select').val(month);
    var qstr=month.split('-');
    getJSONData(host+'/data?act=areayear&year='+qstr[0],function(data){
        if(data.Error==null){
          var okStatus = false;
            data.Data.forEach(function(e){
                var yldays,jzyldays,id=e.areaid;
                if(id==16){
                    if(parseInt(qstr[0])==2016){
                        if(e.monthtype==200+parseInt(qstr[1])){
                            yldays=e.yldays;
                            jzyldays=e.jzyldays;
                        }
                    }else{
                        yldays=e.yldays;
                        jzyldays=e.jzyldays;
                    }
                    if(yldays!=undefined&&jzyldays!=undefined){
                      okStatus = true;
                        var year=qstr[0],m1=year%4==0?29:28,m2=(year-1)%4==0?29:28;
                        var days=getDaysInYear(qstr[0],parseInt(qstr[1],10));
                        var g=yldays/days,g2=jzyldays/(days+m2-m1),v=getGrowth(yldays,jzyldays),v=g-g2,c=v>=0?c1:c2,vt=(Math.abs(v).toFixed(3)*100)+' 个百分点',t=v>0?'<span class="higcolor">增长'+vt+'</span>':(v==0?'<span class="equcolor">持平</span>':'<span class="lowcolor">降低'+vt+'</span>');
                        // (较2015年同期优良天数，完成率为'+g+'%)<br/>
                        var __m=qstr[1]-1+1;
                        // c.title=''+qstr[0]+'年'+(__m>1?'1——'+__m:__m)+'月,全市建成区空气质量达到国家二级标准天数 <b>'+yldays+'</b> 天,达标率为 <b>'+(g*100).toFixed(1)+'%，同比上年'+t;
                        // console.log(g,g2);
                        c.title='优良天数 <span class="days">'+yldays+'</span> 天 '+'<br/>去年同期 <span class="old_year">'+jzyldays+'</span> 天 <br/>优良率较去年同期<br/>'+t;

                        var chart1=new __gauge('#chart-1',0, c);
                        chart1.update(g*100);
                        $('#chart-1-title').html(c.title);
                    }
                }
            });
          //无数据的情况去取上一个月的数据
            if(!okStatus){
              var idx = $("option:selected", "#ylv-month-select").index()
              ,len = $("option", "#ylv-month-select").length;
              if((idx+1)<=(len-1) && len>1){
                //轮询防止异步冲突
                var tmpTimeOutQuery = function(){
              var val = $("option:eq("+(idx+1)+")", "#ylv-month-select").val();
            setYlvChart(val);
                  var svg = $("svg", "#chart-1");
                  if(svg && svg.length>0){
                    //do nothing end.
                  }else{
              setTimeout(tmpTimeOutQuery, 1);
                  }
                }
            setTimeout(tmpTimeOutQuery, 1);
              }
            }
        }
    });
}
function getDaysInYear(year,month){
    var i=1,l=month;
    var days=0;
    for(;i<=l;i++){
        days+=getDaysInMonth(year,i);
    }
    return days;
}
function getDaysInMonth(year,month){ 
    month = parseInt(month,10);
    var temp = new Date(year,month,0); 
    return temp.getDate(); 
}
  var myChart,__type=0;
  var AllCitys=["海门","鄂尔多斯","招远","舟山","齐齐哈尔","盐城","赤峰","青岛","乳山","金昌","泉州","莱西","日照","胶南","南通","拉萨","云浮","梅州","文登","上海","攀枝花","威海","承德","厦门","汕尾","潮州","丹东","太仓","曲靖","烟台","福州","瓦房店","即墨","抚顺","玉溪","张家口","阳泉","莱州","湖州","汕头","昆山","宁波","湛江","揭阳","荣成","连云港","葫芦岛","常熟","东莞","河源","淮安","泰州","南宁","营口","惠州","江阴","蓬莱","韶关","嘉峪关","广州","延安","太原","清远","中山","昆明","寿光","盘锦","长治","深圳","珠海","宿迁","咸阳","铜川","平度","佛山","海口","江门","章丘","肇庆","大连","临汾","吴江","石嘴山","沈阳","苏州","茂名","嘉兴","长春","胶州","银川","张家港","三门峡","锦州","南昌","柳州","三亚","自贡","吉林","阳江","泸州","西宁","宜宾","呼和浩特","成都","大同","镇江","桂林","张家界","宜兴","北海","西安","金坛","东营","牡丹江","遵义","绍兴","扬州","常州","潍坊","重庆","台州","南京","滨州","贵阳","无锡","本溪","克拉玛依","渭南","马鞍山","宝鸡","焦作","句容","北京","徐州","衡水","包头","绵阳","乌鲁木齐","枣庄","杭州","淄博","鞍山","溧阳","库尔勒","安阳","开封","济南","德阳","温州","九江","邯郸","临安","兰州","沧州","临沂","南充","天津","富阳","泰安","诸暨","郑州","哈尔滨","聊城","芜湖","唐山","平顶山","邢台","德州","济宁","荆州","宜昌","义乌","丽水","洛阳","秦皇岛","株洲","石家庄","莱芜","常德","保定","湘潭","金华","岳阳","长沙","衢州","廊坊","菏泽","合肥","武汉","大庆","淮南","滁州","香港","澳门","台北","草场门","中华门","瑞金路","玄武湖","山西路","迈皋桥","仙林大学城","奥体中心","浦口","江宁彩虹桥","高淳淳溪","六合雄州","溧水永阳"];
  var SHCitys=['北京','上海','天津','重庆','哈尔滨','长春','沈阳','呼和浩特','石家庄','乌鲁木齐','兰州','西宁','西安','银川','郑州','济南','太原','合肥','武汉','长沙','南京','成都','贵阳','昆明','南宁','拉萨','杭州','南昌','广州','福州','海口','深圳','台北','香港','澳门'];
  var JSCitys  = ['盐城','南通','扬州','泰州','镇江','宿迁','苏州','淮安','常州','连云港','无锡','南京','徐州'];
  var CSJCitys = ['上海','杭州','宁波','绍兴','湖州','嘉兴','舟山','台州','合肥','马鞍山','金华','衢州','芜湖','滁州','淮南','丽水','温州','盐城','南通','扬州','泰州','镇江','宿迁','苏州','淮安','常州','连云港','无锡','南京','徐州'];
  var NJCitys=['南京','草场门','中华门','瑞金路','玄武湖','山西路','迈皋桥','仙林大学城','奥体中心','浦口','江宁彩虹桥','高淳淳溪','六合雄州','溧水永阳'];
  var __cache__={};
  var AllAQIs={},BMapExt,map,container;
  (function () {
    require.config({
        paths: {
            echarts: './assets/echart',
            d3:'./assets/js/d3.v3.min',
            gauge:'./assets/js/gauge',
            jquery:'./assets/js/jquery'
        },
        packages: [
            {
                name: 'BMap',
                location: './assets/bmap',
                main: 'main'
            }
        ]
    });
    require(['gauge'],function(gauge){
        __gauge=gauge;
        var _currentYear=currentYear,
            _currentMonth=currentMonth;
        //小于半个月默认为上一个月：TODO改为数据判断，如果无数据则为上一个月
        //if(currentDay<15) _currentMonth-=1;
        if(_currentMonth==0){
          _currentMonth=12;
          _currentYear-=1;
        }else if(_currentMonth==-1){
          _currentMonth=11;
          _currentYear-=1;
        }
        setYlvChart(_currentYear+'-'+paddingZero(_currentMonth));
    });
    return;
    
  })();
function getCitys(type){
  __type=type;
  if(type<=7){
    return AllCitys
  }else{
    return [].concat(NJCitys,AllCitys)
  }
}
function getAQI(aqi){
  var num=parseInt(aqi);
  if(isNaN(num)) return null;
  return num
}


